package com.webide;

import org.atmosphere.cpr.AtmosphereServlet;
import org.atmosphere.cpr.ContainerInitializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Collections;

@Configuration
@SpringBootApplication
public class Application {

    /**
     * 注册AtmosphereServlet，并把AtmosphereServlet映射到'/chat'
     * @return  ServletRegistrationBean
     */
    @Bean
    public ServletRegistrationBean atmosphereServlet() {
        // AtmosphereServlet被映射到'/chat'
        ServletRegistrationBean registration = new ServletRegistrationBean(
                new AtmosphereServlet(), "/chat/*");
        registration.addInitParameter("org.atmosphere.cpr.packages", "com");
        registration.addInitParameter("org.atmosphere.interceptor.HeartbeatInterceptor"
                + ".clientHeartbeatFrequencyInSeconds", "10");
        //设置servlet被载入的顺序，0表示容器在应用启动时就加载并初始化这个servlet
        registration.setLoadOnStartup(0);
        //需要在EmbeddedAtmosphereInitializer之前完成
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registration;
    }

    /**
     * 启动容器时加载Atmosphere相关配置
     */
    private static class EmbeddedAtmosphereInitializer extends ContainerInitializer
            implements ServletContextInitializer {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            onStartup(Collections.<Class<?>> emptySet(), servletContext);
        }

    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}
